package com.yonyou.brigade.cron.user.ctripBC;

import com.dangdang.ddframe.job.api.ShardingContext;
import com.dangdang.ddframe.job.api.simple.SimpleJob;
import com.yonyou.brigade.basic_init.enums.ChannelEnum;
import com.yonyou.brigade.basic_init.model.BriChannel;
import com.yonyou.brigade.basic_init.service.IBriChannelService;
import com.yonyou.brigade.basic_init.service.IDeveloperService;
import com.yonyou.brigade.third_parties.ctripBC.service.ICtripBCPublicService;
import com.yonyou.ybzboot.starter.elasticjob.lite.annotation.ElasticJobConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;

import java.util.List;

@ElasticJobConfig(cron = "0 30 6 * * ?", shardingTotalCount = 1)
public class SyncCtripBCUserJob implements SimpleJob {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Value("${brigade.cur}")
    private String curEnv;

    @Autowired
    private IBriChannelService briChannelService;

    @Autowired
    private IDeveloperService developerService;

    @Autowired
    private ICtripBCPublicService ctripBCPublicService;

    @Override
    public void execute(ShardingContext shardingContext) {
        if ("develop".equals(curEnv)) {
            return;
        }
        logger.info("<<<<ctripBC-sync-users-begin>>>>");
        List<BriChannel> briChannels = briChannelService.getEnableChannelByChannel(ChannelEnum.CTRIPBC.getName());
        if (briChannels != null && briChannels.size() > 0) {
            briChannels.forEach(briChannel -> {
                String tenantId = briChannel.getTenant();
                try {
                    if (BriChannel.SYNCUSER == briChannel.getSyncUser()) {
                        ctripBCPublicService.syncAllUsersToCtripBC(tenantId, briChannel.getOrgpk(), briChannel.getOpenType(), briChannel);
                    }
                } catch (Exception e) {
                    logger.error(tenantId + "租户" + briChannel.getChannel() + "渠道（渠道id为" + briChannel.getId() + "）同步人员失败");
                    developerService.sendEmailToDev(curEnv, briChannel.getChannel(), "同步人员", e);
                }
            });
        }
        logger.info("<<<<ctripBC-sync-users-end>>>>");
    }
}
